package com.ruoyi.know.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.know.domain.PointRecords;
import com.ruoyi.know.mapper.PointRecordsMapper;
import com.ruoyi.know.service.IPointRecordsService;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 积分记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-14
 */
@Service
public class PointRecordsServiceImpl implements IPointRecordsService
{
    @Autowired
    private PointRecordsMapper pointRecordsMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询积分记录
     *
     * @param id 积分记录主键
     * @return 积分记录
     */
    @Override
    public PointRecords selectPointRecordsById(Long id)
    {
        return pointRecordsMapper.selectPointRecordsById(id);
    }

    public Integer selectTotalPoints(Long userId)
    {
        return pointRecordsMapper.selectTotalPoints(userId);
    }

    /**
     * 查询积分记录列表
     *
     * @param pointRecords 积分记录
     * @return 积分记录
     */
    @Override
    public List<PointRecords> selectPointRecordsList(PointRecords pointRecords)
    {
        return pointRecordsMapper.selectPointRecordsList(pointRecords);
    }

    /**
     * 新增积分记录
     *
     * @param pointRecords 积分记录
     * @return 结果
     */
    @Override
    public int insertPointRecords(PointRecords pointRecords)
    {
        return pointRecordsMapper.insertPointRecords(pointRecords);
    }

    /**
     * 修改积分记录
     *
     * @param pointRecords 积分记录
     * @return 结果
     */
    @Override
    public int updatePointRecords(PointRecords pointRecords)
    {
        return pointRecordsMapper.updatePointRecords(pointRecords);
    }

    /**
     * 批量删除积分记录
     *
     * @param ids 需要删除的积分记录主键
     * @return 结果
     */
    @Override
    public int deletePointRecordsByIds(Long[] ids)
    {
        return pointRecordsMapper.deletePointRecordsByIds(ids);
    }

    /**
     * 删除积分记录信息
     *
     * @param id 积分记录主键
     * @return 结果
     */
    @Override
    public int deletePointRecordsById(Long id)
    {
        return pointRecordsMapper.deletePointRecordsById(id);
    }

    private static final Map<String, Integer> ACTION_POINTS = new HashMap<>();
    static {
        ACTION_POINTS.put("浏览知识点", 1);
        ACTION_POINTS.put("点赞", 2);
        ACTION_POINTS.put("评论", 3);
        ACTION_POINTS.put("发布笔记", 5);
        ACTION_POINTS.put("发布帖子", 6);
    }
    private static final Map<String, Integer> LEVEL_POINTS = new HashMap<>();
    static {
        LEVEL_POINTS.put("白银-黄金", 500);
        LEVEL_POINTS.put("黄金-铂金", 1000);
        LEVEL_POINTS.put("铂金-钻石", 1500);
    }

    @Override
    public void earnPoints(Long userId, String actionType, boolean isAdd) {
        SysUser user = sysUserMapper.selectUserById(userId);
        int pointsToEarn = ACTION_POINTS.getOrDefault(actionType, 0);
        //更新用户积分
        if(isAdd){
            user.setPoints(user.getPoints() + pointsToEarn);
        }else {
            user.setPoints(user.getPoints() - pointsToEarn);
        }
        sysUserMapper.updateUser(user);
        //保存积分记录
        PointRecords record = new PointRecords();
        record.setUserId(userId);
        record.setActionType(actionType);
        record.setPointsEarned(pointsToEarn);
        record.setCreatedAt(new Date());
        pointRecordsMapper.insertPointRecords(record);
        //更新等级
        updateUserLevel(user);
    }

    /**
     * 等级计算逻辑
     * @param user
     */
    private void updateUserLevel(SysUser user) {
        int points = user.getPoints();
        String currentLevel = getUserLevel(points);
        if ("白银".equals(currentLevel) && points >= LEVEL_POINTS.get("白银-黄金")) {
            Long[] roleIds = {100L};
            insertUserRole(user.getUserId(), roleIds);
        } else if ("黄金".equals(currentLevel) && points >= LEVEL_POINTS.get("黄金-铂金")) {
            Long[] roleIds = {101L};
            insertUserRole(user.getUserId(), roleIds);
        } else if ("铂金".equals(currentLevel) && points >= LEVEL_POINTS.get("铂金-钻石")) {
            Long[] roleIds = {102L};
            insertUserRole(user.getUserId(), roleIds);
        }

    }

    /**
     * 根据积分获取用户等级
     *
     * @param points 用户积分
     * @return 用户等级
     */
    private String getUserLevel(int points) {
        if (points < 500) {
            return "白银";
        } else if (points < 1000) {
            return "黄金";
        } else if (points < 1500) {
            return "铂金";
        } else {
            return "钻石";
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysUserRoleMapper.batchUserRole(list);
        }
    }
}
